var express = require("express");
var router = express.Router();

const UserModel = require("../../models/UserModel");
const md5 = require("md5");

// 注册
router.get("/reg", (req, res) => {
  // 响应 HTTP
  res.render("auth/reg");
});

// 获取注册的内容
router.post("/reg", (req, res) => {
  // 响应 HTTP
  UserModel.create(
    { ...req.body, password: md5(req.body.password) },
    (err, data) => {
      if (err) {
        res.status(500).send("注册失败！");
        return;
      }
      res.render("success", { msg: "注册成功！", url: "/login" });
    }
  );
});

// 登录
router.get("/login", (req, res) => {
  // 响应 HTTP
  res.render("auth/login");
});

// 获取登录的内容
router.post("/login", (req, res) => {
  const { username, password } = req.body;
  UserModel.findOne(
    { username: username, password: md5(password) },
    (err, data) => {
      if (err) {
        res.status(500).send("登录失败！");
        return;
      }
      if (!data) {
        res.status(500).send("用户名或密码不存在！");
        return;
      }
      // 写入session
      req.session.username = data.username;
      req.session._id = data._id;
      // 登录成功响应
      res.render("success", { msg: "登录成功！", url: "/account" });
    }
  );
});

// 退出登录
router.post("/logout", (req, res) => {
  req.session.destroy(() => {
    res.render("success", { msg: "退出成功！", url: "/login" });
  });
});

module.exports = router;
